<template>
  <div>
    <div v-model="searchData" style="margin: 10px 0">
      <el-input v-model="searchData.name" style="width: 200px" placeholder="请输入名称"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="rest">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="addHander">新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="Id" width="60"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="info" @click="menuManage(scope.row)">菜单管理 <i class="el-icon-menu"></i></el-button>
          <el-button type="success" @click="handleEdit(scope.row.id),updateFormVisible=true">编辑 <i
              class="el-icon-edit"></i></el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="新增角色信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" label-width="80px" size="small">
        <el-form-item label="名字">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改用户信息" :visible.sync="updateFormVisible" width="30%">
      <el-form :model="info" label-width="80px" size="small">
        <el-form-item label="名字">
          <el-input v-model="info.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="info.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="菜单" :visible.sync="menuFormVisible" width="30%">
      <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expanded"
          :default-checked-keys="checks">
        <span class="custom-tree-node" slot-scope="{ node, data }">
        <span><i :class="data.icon"/> {{ data.name }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      menuData: [],
      props: {
        label: 'name'
      },
      multipleSelection: [],
      searchData: {
        name: ''
      },
      form: {},
      info: {},
      tableData: [],
      headerBg: 'headerBg',
      current: 1,
      total: 1,
      pageSize: 5,
      dialogFormVisible: false,
      updateFormVisible: false,
      menuFormVisible: false,
      expanded: [],
      checks: [],
      roleId: 0,
      roleName: ''
    }
  },
  created() {
    this.load()
  },
  methods: {
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
      console.log(this.multipleSelection.map(v => v.id))
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //[1,2,3]
      this.$confirm('此操作将删除这些用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/role/delete/batch/" + ids).then(resp => {
          if (resp.data) {
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    del(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/role/delete/" + id).then(resp => {
          if (resp.data) {
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addHander() {
      this.dialogFormVisible = true
      this.form = {}
    },

    rest() { //重置搜索栏
      this.searchData.name = ''
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log("每页条数: " + pageSize)
      this.pageSize = pageSize;
      this.load()
    },
    handleCurrentChange(current) {
      console.log("当前页码: " + current)
      this.current = current;
      this.load()
    },
    collapse() {  // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse
      if (this.isCollapse) {  // 收缩
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      } else {   // 展开
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    },
    load() {
      this.request.get("/role/page", {
            params: {
              current: this.current,
              pageSize: this.pageSize,
              name: this.searchData.name,
            }
          }
      ).then(resp => {
        console.log(resp)
        this.tableData = resp.data.records
        this.total = resp.data.total
      })
    },
    save() {//新增用户
      this.request.post("/role/save", this.form).then(resp => {
        console.log(resp)
        if (resp.data) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
          this.load()
        }
      })
    },
    //编辑
    handleEdit(id) {
      console.log(id)
      this.request.get("/role/" + id).then(resp => {
        console.log("根据id查到的数据")
        console.log(resp)
        this.info = resp.data
      })
      this.updateFormVisible = true
    },
    //更新数据
    update() {
      this.request.put("/role/update/", this.info).then(resp => {
        console.log(resp)
        if (resp.data) {
          this.$message.success("更新成功")
          this.updateFormVisible = false
          this.load()
        } else {
          this.$message.error("更新失败")
        }
      })
    },
    //菜单管理
    menuManage(role) {
      this.menuFormVisible = true
      this.roleId = role.id
      this.roleName = role.name

      //请求菜单数据
      this.request.get("/menu").then(res => {
        this.menuData = res.data
        this.props = res.data.name

        //把后台返回的菜单数据处理成 id数组
        this.expanded = this.menuData.map(m => m.id)
      })

      //设置默认选中
      this.request.get("/role/roleMenu/" + this.roleId).then(res => {
        this.checks = res.data

        this.request.get("/menu/ids").then(res=>{
         const ids = res.data
          ids.forEach(id=>{
            if (!this.checks.includes(id)){
              this.$refs.tree.setChecked(id,false)
            }
          })
        })
      })
    },
    updateRoleMenu() {
      console.log(this.$refs.tree.getCheckedKeys());
      this.request.post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then(res => {

          if (res.code === 200) {
            this.$message.success("绑定成功")
            this.menuFormVisible = false

            console.log(this.roleName)
            //操作管理员角色后需要重新登录
            if (this.roleName==='管理员'){
              this.$store.commit("logout")
            }

          } else {
            this.$message.error("绑定失败")
          }
      })
    }
  }
}
</script>

<style>
.headerBg {
  background: #eee !important;
}
</style>